package com.cays.myresearch.activity;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ScrollView;
import android.widget.Toast;

import com.cays.myresearch.R;
import com.cays.myresearch.Util.HttpUtil;
import com.cays.myresearch.action.LoginAction;
import com.cays.myresearch.adapter.ProjectsAdapter;
import com.cays.myresearch.constant.Constant;
import com.cays.myresearch.entity.Projects;
import com.cays.myresearch.entity.ResponseInfo;
import com.cays.myresearch.ui.HeadControlPanel;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import okhttp3.MultipartBody;

public class ProjectActivity extends AppCompatActivity implements
    HeadControlPanel.HeadPanelCallback,ProjectsAdapter.ProjectsClickListener{
    private HeadControlPanel projectHeader;
    private boolean myProject=false,myAttendProject=false;
    private PtrFrameLayout projectRefresh;
    private RecyclerView pRecycleView;
    private List<Projects> projectList=new ArrayList<>();
    private ProjectsAdapter projectsAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myProject=getIntent().getBooleanExtra("my_project",false);
        myAttendProject=getIntent().getBooleanExtra("my_attend_project",false);
        setContentView(R.layout.activity_project);
        if (getSupportActionBar()!=null){getSupportActionBar().hide();}
        if(projectHeader==null){
            projectHeader=(HeadControlPanel)findViewById(R.id.project_header);
            projectHeader.initHeadPanel();
            projectHeader.setHeadPanelCallback(this);
        }
        projectHeader.setLeftImage(R.drawable.ic_back);
        if (myProject){
            projectHeader.setMiddleTitle("我的项目");
        }else if (myAttendProject){
            projectHeader.setMiddleTitle("我参加的项目");
        }else {
            projectHeader.setMiddleTitle("项目列表");
        }
        projectHeader.setRightTitle("");
        initView();initFresh();
    }
    private void initView(){
        projectList.clear();
        projectRefresh = (PtrFrameLayout) findViewById(R.id.project_refresh);
        pRecycleView = (RecyclerView) findViewById(R.id.project_list);
        GridLayoutManager gridLayoutManager=new GridLayoutManager(getApplicationContext(),1);
        pRecycleView.setLayoutManager(gridLayoutManager);
        projectsAdapter=new ProjectsAdapter(projectList);
        pRecycleView.setAdapter(projectsAdapter);
        projectsAdapter.setProjectsClickListenerListener(this);
    }
    public void initFresh(){
        //这里是一个自定义的头部刷新布局,自带的也有一个布局   new PtrDefaultHandler();
        PtrClassicDefaultHeader header = new PtrClassicDefaultHeader(this);
        projectRefresh.addPtrUIHandler(header);
        //不仅仅是添加头布局,还需要设置到控件中 注:特别重要,不然没显示
        projectRefresh.setHeaderView(header);
        projectRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                //执行调用下拉刷新监听
                projectRefresh.autoRefresh(true);
            }
        },200);
        //设置下拉刷新监听
        projectRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                // 默认实现，根据实际情况做改动
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //在这里写自己下拉刷新数据的请求
                //需要结束刷新头
                refreshProject();
            }
        });
    }
    @Override
    public void onHeadPanelClick(int itemId) {
        switch (itemId){
            case Constant.btn_left_title:
                finish();
                break;
            case Constant.btn_middle_title:
                refreshProject();
                break;
            case Constant.btn_right_title:
                refreshProject();
                break;
            default:break;
        }
    }
    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what==0){
                Toast.makeText(getApplicationContext(),"未知错误",Toast.LENGTH_SHORT).show();
            }else if (msg.what==1){
                String s=(String)msg.obj;
                String []s1=s.split("~");
                ResponseInfo responseInfo=Constant.gson.fromJson(s1[0],
                        new TypeToken<ResponseInfo>(){}.getType());
                if (s.contains("~")){
                    List<Projects> pList=Constant.gson.fromJson(s1[1],
                            new TypeToken<List<Projects>>(){}.getType());
                    projectList.clear();projectList.addAll(pList);
                }
                Toast.makeText(getApplicationContext(),responseInfo.getResponseInfo(),
                        Toast.LENGTH_SHORT).show();
            }
            projectsAdapter.notifyDataSetChanged();
            projectRefresh.refreshComplete();
            return true;
        }
    });
    private void refreshProject(){
        final String url;
        if (myProject){
            LoginAction action=new LoginAction();
            if (!action.hasUserInfo(getApplicationContext())){
                Toast.makeText(this,"未登录",Toast.LENGTH_SHORT).show();
                projectList.clear();
                projectsAdapter.notifyDataSetChanged();
                projectRefresh.refreshComplete();
                return;
            }
            url=Constant.URL+"project/my_project";
            final MultipartBody.Builder builder=new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);
            builder.addFormDataPart("name",action.getName(getApplicationContext()));
            HttpUtil.sendHttpRequest(url,builder,handler,1,0);
        }else if (myAttendProject){
            LoginAction action=new LoginAction();
            if (!action.hasUserInfo(getApplicationContext())){
                Toast.makeText(this,"未登录",Toast.LENGTH_SHORT).show();
                projectList.clear();
                projectsAdapter.notifyDataSetChanged();
                projectRefresh.refreshComplete();
                return;
            }
            url=Constant.URL+"project/my_project";
            final MultipartBody.Builder builder=new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);
            builder.addFormDataPart("name",action.getName(getApplicationContext()));
            HttpUtil.sendHttpRequest(url,builder,handler,1,0);
        }else {
            url=Constant.URL+"project/list";
            HttpUtil.sendHttpRequest(url,handler,1,0);
        }
    }

    @Override
    public void onProjectsClick(View item, int position) {

    }
}
